// ignore_for_file: use_build_context_synchronously, prefer_const_constructors

import 'dart:async';
import 'dart:math';
import 'dart:ui';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:junyeyishu/ui/mine/widget/QGMineItemWidget.dart';

import 'package:junyeyishu/utils/utils.dart';
import 'package:flutter/services.dart';
import 'package:junyeyishu/widgets/QGWidget.dart';
import 'package:junyeyishu/widgets/QGUserNavigationBar.dart';

class QGMinePage extends StatefulWidget {
  const QGMinePage({super.key});
  @override
  State<QGMinePage> createState() => _QGMinePageState();
}

class _QGMinePageState extends State<QGMinePage> {
  Map<String, dynamic>? userInfo;
  EasyRefreshController refreshController = EasyRefreshController();

  bool checkHF = false;
  bool hasBatch = false;
  int type = 0;

  StreamSubscription? listener;
  StreamSubscription? listenerTheme;

  @override
  void dispose() {
    listener?.cancel();
    listenerTheme?.cancel();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    eventBus.on<EventMainTabRefresh>().listen((event) {
      if (event.index != 3) return;
      onRefresh();
    });

    onRefresh();

    listener = eventBus.on<EventLogin>().listen((obj) {
      onRefresh();
    });
  }

  onRefresh() {
    Network.get(url_u_getMergedUserInfo).then((res) async {
      if (!res.success) {
        toast(res.msg);

        //处理token失效的情形
        if (!User.isLogin) {
          await Future.delayed(const Duration(seconds: 2));
          Navigator.of(context).pushNamed(PageLogin).then((value) {
            if (!User.isLogin) {
              eventBus.fire(EventMainTabSelectIndex(index: 0));
            }
          });
        }
        return;
      }

      userInfo = res.data?["user_info"];
      checkHF = res.data?["huifu_wallet"] == 1;
      hasBatch = res.data?["batch_buy"] == 1;
      print(userInfo);

      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Container(
            child: EasyRefresh(
              controller: refreshController,
              onRefresh: onRefresh,
              child: ListView(
                padding: EdgeInsets.zero,
                children: [
                  Stack(
                    children: [
                      buildImage(),
                      Column(
                        children: [
                          buildTop(),
                          SizedBox(height: 20.rpx),
                          buildList(),
                          SizedBox(height: 10.rpx),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  buildImage() {
    return QGImage(asset: "mine_head_bg", width: 375.rpx);
  }

  buildTop() {
    return SizedBox(
      width: kScreenWidth,
      child: Column(
        children: [
          QGUserNavigationBar(
            title: '',
          ),
          buildMineInfo(),
        ],
      ),
    );
  }

  buildMineInfo() {
    return Container(
      width: kScreenWidth,
      padding: EdgeInsets.fromLTRB(15.rpx, 10.rpx, 15.rpx, 0.rpx),
      child: Column(
        children: [
          SizedBox(height: 10.rpx),
          buildMineAccount(),
          SizedBox(height: 30.rpx),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            buildMineName(),
            buildMineAvatar()
          ]
        ),

          SizedBox(height: 20.rpx),

          SizedBox(height: 20.rpx),
          buildMineOperation()
        ],
      ),
    );
  }

  buildMineAccount() {
    return GestureDetector(
      onTap: toUserInfo,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // buildMineAvatar(), // cangping   qianbao  dingdan anquzn  haoyou  pangdan rjiantou
          QGImage(width: 60.rpx,asset: 'junyue'),
          QGImage(asset: 'mine_set_icon', width: 35.rpx),
          // SizedBox(width: 15.rpx),
          //buildMineName(),
          // SizedBox(width: 15.rpx),
          // Container(
          //   color: Colors.transparent,
          //   padding: EdgeInsets.fromLTRB(10.rpx, 7.rpx, 0, 7.rpx),
          //   child: QGImage(asset: 'mine_set_icon', width: 24.rpx),
          // ),
        ],
      ),
    );
  }

  buildMineAvatar() {
    return GestureDetector(
      onTap: toUserInfo,
      child: 
                  CircleAvatar(   
                    radius: 50.rpx,
                    backgroundImage:NetworkImage('${userInfo?["avatar"]}')
                  ),
    
    );
  }

  buildMineName() {
    return  
    Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            userInfo?["nickname"] ?? '',
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
                fontSize: 20.rpx,
                fontWeight: FontWeight.bold,
                color: Color(0xFFffffff)),
          ),
          SizedBox(height: 5.rpx),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              Clipboard.setData(ClipboardData(text: '${userInfo?["id"]}'));
              toast('复制成功');
            },
            child: Row(
              children: [
                Text(
                  'UID: ${userInfo?["id"] ?? ''}',
                  style: TextStyle(
                      fontSize: 13.rpx,
                      fontWeight: FontWeight.normal,
                      color: Color(0xFFffffff)),
                ),
                SizedBox(
                  width: 7.rpx,
                ),
                QGImage(asset: "mine_copy_address",width: 13.rpx),
              ],
            ),
          ),
          SizedBox(height: 5.rpx),

          buildAddress()
        ],
      );
  }

  buildAddress() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        Clipboard.setData(ClipboardData(text: '${userInfo?["address"]}'));
        toast('复制成功');
      },
      child: Row(
                  children: [
                    Text(
                      '区块链地址：',
                      style: TextStyle(
                          fontSize: 12.rpx,
                          fontWeight: FontWeight.normal,
                          color: Color(0xFFffffff)),
                    ),
                  Text(
                        '${userInfo?["address"].substring(0,10) ?? ""}...',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 12.rpx,
                            fontWeight: FontWeight.normal,
                            color: Color(0xFFffffff)),
                      ),
          SizedBox(width: 5.rpx),

                      QGImage(asset: "mine_copy_address",width: 13.rpx),
                  ],
                ),
    );
  }

  buildMineOperation() {
    return Container(
      child: Row(
        children: [
         
          Expanded(child: 
           GestureDetector(
            onTap: (){
                toMyNft();
            },
            child: QGImage(asset: "cangping"),
          )
          ),
          SizedBox(width: 15.rpx,),
            Expanded(child: 
            GestureDetector(
            onTap: (){
                toWallet();
            },
            child:
            QGImage(asset: "qianbao")
            )
          ),
          // QGImage(asset: "qianbao"),

          // buildMineOperationItem("我的藏品", "mine_info_collection", toMyNft),
          // inReview()
          //     ? Container()
          //     :
          //      Container(
          //         width: 0.5.rpx, height: 25.rpx, color: Color(0xFF979797)),
          // inReview()
          //     ? Container()
          //     : buildMineOperationItem("我的钱包", "mine_info_wallet", toWallet)
        ],
      ),
    );
  }

  Widget buildMineOperationItem(
      String title, String icon, VoidCallback onPressed) {
    return GestureDetector(
      onTap: onPressed,
      child: Container(
        color: Colors.transparent,
        padding: EdgeInsets.symmetric(horizontal: 10.rpx, vertical: 15.rpx),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // QGImage(asset: icon, width: 30.rpx, height: 30.rpx),
            // SizedBox(width: 12.rpx),
            Text(
              title,
              style: TextStyle(
                  fontSize: 15.rpx,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF111111)),
            )
          ],
        ),
      ),
    );
  }

  buildList() {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.symmetric(horizontal: 15.rpx),
      padding: EdgeInsets.symmetric(horizontal: 10.rpx, vertical: 20.rpx),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.rpx),
        color: Color(0xFF232A32),
      ),
      child: Column(
        children: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,

            onTap: (){
              toFirstOrder();
            },
            child:Row(
            children: [
              QGImage(asset: 'dingdan', width: 25.rpx),
              SizedBox(width: 5.rpx,),
              Text('我的订单',style: TextStyle(fontSize: 16,color: Color(0XFFFFFFFF))),
              Expanded(child: SizedBox()),
              QGImage(asset: 'rjiantou', width:8.rpx),
            ],
          ),
          )
          ,
          inReview() ? Container() : SizedBox(height: 20.rpx),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: (){
              toUserInfo1();
            },
      child: Row(
            children: [
              QGImage(asset: 'anquzn', width: 25.rpx),
              SizedBox(width: 5.rpx,),
              Text('账号安全',style: TextStyle(fontSize: 16,color: Color(0XFFFFFFFF))),
              Expanded(child: SizedBox()),
              QGImage(asset: 'rjiantou', width: 8.rpx),
            ],
          ),
          )
          ,
          inReview() ? Container() : SizedBox(height: 20.rpx),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: (){
              toInvite();
            },
      child: 
           Row(
            children: [
              QGImage(asset: 'haoyou', width: 25.rpx),
              SizedBox(width: 5.rpx,),
              Text('邀请好友',style: TextStyle(fontSize: 16,color: Color(0XFFFFFFFF))),
              Expanded(child: SizedBox()),
              QGImage(asset: 'rjiantou', width: 8.rpx),
            ],
          )),
          inReview() ? Container() : SizedBox(height: 20.rpx),
          
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: (){
              toInvite1();
            },
      child: 
           Row(
            children: [
              QGImage(asset: 'pangdan', width: 25.rpx),
              SizedBox(width: 5.rpx,),
              Text('排行榜单',style: TextStyle(fontSize: 16,color: Color(0XFFFFFFFF))),
              Expanded(child: SizedBox()),
              QGImage(asset: 'rjiantou', width: 8.rpx),
            ],
          ),
          ),

          // Row(
          //   mainAxisAlignment: MainAxisAlignment.start,
          //   children: [
          //     inReview()
          //         ? Container()
          //         : QGMineItem(
          //             icon: 'mine_order_icon',
          //             name: '寄售订单',
          //             opacity: 1,
          //             onPressed: toMyOrder),
          //     inReview()
          //         ? Container()
          //         : QGMineItem(
          //             icon: 'mine_purchase_icon',
          //             name: '求购订单',
          //             opacity: 1,
          //             onPressed: toMyPurchaseOrder),
          //     inReview()
          //         ? Container()
          //         : QGMineItem(
          //             icon: 'mine_first_icon',
          //             name: '一级订单',
          //             opacity: 1,
          //             onPressed: toFirstOrder),
          //     QGMineItem(
          //         icon: 'mine_zhuan_icon',
          //         name: '转赠记录',
          //         opacity: 1,
          //         onPressed: toSend),
          //     inReview()
          //         ? QGMineItem(
          //             icon: 'mine_authent_icon',
          //             name: '我的认证',
          //             opacity: 1,
          //             onPressed: toAuthent)
          //         : Container()
          //   ],
          // ),
          // inReview() ? Container() : SizedBox(height: 20.rpx),
          // Row(
          //   mainAxisAlignment: MainAxisAlignment.start,
          //   children: [
          //     inReview()
          //         ? Container()
          //         : QGMineItem(
          //             icon: 'mine_authent_icon',
          //             name: '我的认证',
          //             opacity: 1,
          //             onPressed: toAuthent),
          //     inReview()
          //         ? Container()
          //         : QGMineItem(
          //             icon: 'mine_invite_icon',
          //             name: '邀请好友',
          //             opacity: 1,
          //             onPressed: toInvite),
          //     inReview()
          //         ? Container()
          //         : Container(
          //             child: hasBatch
          //                 ? QGMineItem(
          //                     icon: 'mine_batch_icon',
          //                     name: '批量订单',
          //                     opacity: 1,
          //                     onPressed: toMyBatchOrder)
          //                 : Container()),
          //   ],
          // ),
        ],
      ),
    );
  }

  toUserInfo() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }
    Navigator.of(context)
        .pushNamed(PageMineAccount, arguments: userInfo)
        .then((value) {
      if (mounted) {
        onRefresh();
      }
    });
  }
    toUserInfo1() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }
    Navigator.of(context)
        .pushNamed(PageMineAccountPagepawss, arguments: userInfo)
        .then((value) {
      if (mounted) {
        onRefresh();
      }
    });
  }

  toWallet() async {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }

    if (!checkHF) {
      var res = await Network.post(url_u_getMergedUserInfo, context: context);
      checkHF = res.data["huifu_wallet"] == 1;
      if (!checkHF) {
        Navigator.of(context).pushNamed(PageSelectWallet);
        return;
      }
    }

    Network.post(url_hf_manageWallet, context: context).then((res) {
      if (!res.success) {
        toast(res.msg);
        return;
        
      }
      var url = res.data["result"];
      Navigator.of(context).pushNamed(PageQGPayWebView, arguments: url);
    });
  }

  toMyNFT() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }
    Navigator.of(context).pushNamed(PageMyNFT);
  }

  toAbout() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }
    if (inReview()) {
      Navigator.of(context).pushNamed(PageAboutUs);
    } else {
      Navigator.of(context).pushNamed(PageAbout);
    }
  }

  toMyNft() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }
    Navigator.of(context).pushNamed(PageMyNFT);
  }

  toMyOrder() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }
    Navigator.of(context).pushNamed(PageMyOrder);
  }

  toMyBatchOrder() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }
    Navigator.of(context).pushNamed(PageMyBatchOrder);
  }

  toMyPurchaseOrder() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }
    Navigator.of(context).pushNamed(PageMyPurchaseOrder);
  }

  toFirstOrder() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }
    Navigator.of(context).pushNamed(PageMyHomeOrder);
  }

  toSend() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }
    Navigator.of(context).pushNamed(PageNFTSendRecord);
  }

  toCart() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }
    Navigator.of(context).pushNamed(PageMyCart);
  }

  toAuthent() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }
    if (userInfo?['realname_check'] == '0') {
      Navigator.of(context).pushNamed(pageMineAuthent).then((value) {
        onRefresh();
      });
    } else {
      Navigator.of(context).pushNamed(pageMineHasAuthent);
    }
  }

  toInvite() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }

    Navigator.of(context).pushNamed(PageInvite);
  }
   toInvite1() {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }

    Navigator.of(context).pushNamed(PageListSingle);
  }
}
